package com.xplay.xpocker.room.mahjong.action;

import com.xplay.xpocker.constant.MessageNoticeEnum;
import com.xplay.xpocker.dvo.GameRuMahjongUserState;
import com.xplay.xpocker.dvo.AbstractRoom;
import com.xplay.xpocker.entity.GameRuMahjongLogs;
import com.xplay.xpocker.room.RoomInfoTL;
import com.xplay.xpocker.room.mahjong.AbstractIsolationEventStrategy;
import com.xplay.xpocker.room.mahjong.AbstractMahjongMessageStrategy;
import com.xplay.xpocker.room.mahjong.constant.MKey;
import com.xplay.xpocker.room.mahjong.dto.*;
import com.xplay.xpocker.room.message.MessageContent;
import com.xplay.xpocker.room.message.MessageContentFactory;
import com.xplay.xpocker.room.message.MessageToClient;
import com.xplay.xpocker.room.message.MessageType;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CellAction extends AbstractMahjongMessageStrategy<AbstractRoom<MahjongRoomRule, MahjongRoomInfo, GameRuMahjongLogs>, MahjongMessage> {

    @Override
    protected String strategyName() {
        return MahjongActionEnum.CALL.getAction();
    }

    /**
     * 注意 听牌过后
     * 点了听牌过后前端需要两个操作
     * 1.不参与碰牌检测
     * 2.杠牌需要判断胡牌是否产生变更
     * 3.
     *
     * @param roomInfo
     * @param messageInfo
     * @return
     */
    @Override
    public boolean doMessage(AbstractRoom<MahjongRoomRule, MahjongRoomInfo,GameRuMahjongLogs> roomInfo, MahjongMessage messageInfo) {
        MahjongRoomInfo gameInfo = roomInfo.getGameInfo();
        GameRuMahjongUserState currentUser = gameInfo.getCurrentUser();
        currentUser.setListen(true);
        // 摸牌听
        if (currentUser.allHandCards().size() % 3 == 2) {
            // 判断是否自摸
            ScoreInfo scoreInfo = AbstractIsolationEventStrategy.getSettlementStrategy(roomInfo.getType())
                    .checkHu(currentUser, null, null, roomInfo);
            if (scoreInfo != null) {
                addWaitCompleted(currentUser, MahjongActionEnum.HU);
            }
            addWaitCompleted(currentUser, MahjongActionEnum.EXPORT_CARD);
            // 通知用户更新action
            notifyUserActionUpdate(currentUser, 0);
        }
        // 构建消息通知
        List<MessageContent<MessageToClient>> callMessageList = MessageContentFactory.
                init(roomInfo.getCode(), MessageType.ACTION.getType(), currentUser.getUserId(), MessageNoticeEnum.ALL)
                .multi(MKey.exeActionUid, currentUser.getUserId(),
                        MKey.type, MahjongActionEnum.CALL.getAction())
                .send().getMessageList();
        RoomInfoTL.addMessageToClient(callMessageList);
        // 将现有的手牌 直接存储到 listenCards
        currentUser.setListenCards(currentUser.allHandCardsStr());
        return true;
    }

}
